package com.mlink.ai.chat.ui.activity

import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import com.adsdk.android.ads.constants.OxSdkConstants
import com.adsdk.android.ads.interstitial.InterstitialAdListener
import com.adsdk.android.ads.interstitial.OxInterstitialAdHelper
import com.cipher.CipherUtils
import com.mlink.ai.chat.AiChatApplication
import com.mlink.ai.chat.ads.AdUtils
import com.mlink.ai.chat.ads.adManager
import com.mlink.ai.chat.assistant.robot.databinding.ActivitySplashBinding
import com.mlink.ai.chat.constants.IS_CLICKED_GET_STARTED_BTN
import com.mlink.ai.chat.constants.isFirstOpenApp
import com.mlink.ai.chat.local.entity.ChatMessageEntity
import com.mlink.ai.chat.network.Api
import com.mlink.ai.chat.network.bean.request.RegisterUserRequest
import com.mlink.ai.chat.ui.viewmodel.RecentViewModel
import com.mlink.ai.chat.utils.ChatLimitUtils
import com.mlink.ai.chat.utils.DeviceUtils
import com.mlink.ai.chat.utils.FileUtils
import com.mlink.ai.chat.utils.LanguageUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.*
import java.io.File

class SplashActivity : BaseActivity<ActivitySplashBinding>() {

    private var oxInterstitialAdHelper: OxInterstitialAdHelper? = null

    private var isResume = false
    private val recentViewModel : RecentViewModel by viewModels()

    @OptIn(DelicateCoroutinesApi::class)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        loadInterstitialAd()

        if (!AiChatApplication.app.appViewModel.isSubscribed()) {
            adManager.loadMainNativeBannerAd()
        }

        if (!LanguageUtils.isLanguageSet() && !AiChatApplication.app.appViewModel.isSubscribed()) {
            adManager.loadLanguageNativeAd()
        }

        if (MMKV.defaultMMKV().decodeInt(ChatLimitUtils.KEY_COUNT_USED, -1) == -1) {
            MMKV.defaultMMKV().encode(ChatLimitUtils.KEY_COUNT_USED, 3)
        }

        /**
         * 删除异常情况下因为图文识别保存的不需要的图片
         */
        if (ChatMessageEntity.isHaveTempData()) {
            recentViewModel.insertHistoryMessage(ChatMessageEntity.getTempData())
        } else {
            if (ChatMessageEntity.isHaveTempPic()) {
                GlobalScope.launch(Dispatchers.IO) {
                    runCatching {
                        val list = ChatMessageEntity.getTempPic()
                        list.forEach {
                            val file = File(it)
                            if (file.exists()) {
                                file.delete()
                            }
                        }
                    }
                    ChatMessageEntity.removeTempPic()
                }
            }
        }

        /**
         * 删除 feedback 功能保存的媒体文件
         */
        GlobalScope.launch(Dispatchers.IO) {
            val dir = File(FileUtils.getCacheDir(this@SplashActivity), "feedback")
            dir.listFiles()?.forEach {
                it.delete()
            }
        }

        lifecycleScope.launch {
            // 延迟 3 秒
            delay(3000)

            if (MMKV.defaultMMKV().decodeBool(IS_CLICKED_GET_STARTED_BTN)) {
                isFirstOpenApp = false

                val isAdReady = oxInterstitialAdHelper?.isReady ?: false
                if (!AiChatApplication.app.appViewModel.isSubscribed() && isAdReady && isResume) {
                    showInterstitialAd()
                } else {
                    oxInterstitialAdHelper?.let {
                        val adConfig = AdUtils.getSplashInterstitialAdConfig(this@SplashActivity)
                        if (AiChatApplication.app.appViewModel.isSubscribed()) {
                            it.onClientShowingLimitation(
                                adConfig.adPlacement,
                                OxSdkConstants.AdShowLimitation.REMOVE_ADS_BY_PURCHASE
                            )
                        } else if (!isAdReady) {
                            it.onClientShowingLimitation(
                                adConfig.adPlacement,
                                OxSdkConstants.AdShowLimitation.AD_NOT_READY
                            )
                        }
                    }

                    startToNextActivity()
                }

            } else {
                isFirstOpenApp = true
                startActivity(Intent(this@SplashActivity, StartActivity::class.java))

                finish()
            }
        }

        // 用户注册
        GlobalScope.launch(Dispatchers.IO) {
            if (MMKV.defaultMMKV()
                    .decodeString((DeviceUtils.PREF_FIREBASE_INSTALLATIONS_ID)) == null
            ) {
                var uidNew = ""
                runCatching {
                    uidNew = DeviceUtils.getUid()
                    val source = uidNew + CipherUtils.getCipherKeyFromJNI()
                    val md5 = CipherUtils.getMD5(source.toByteArray())
                    Api.chatApi.doRegisterUser(RegisterUserRequest(uidNew, md5))
                }.onSuccess {
                    if (it.ret == 200) {
                        MMKV.defaultMMKV()
                            .putString(DeviceUtils.PREF_FIREBASE_INSTALLATIONS_ID, uidNew)
                    }
                }
            }
        }
    }

    override fun getViewBinding(): ActivitySplashBinding {
        return ActivitySplashBinding.inflate(layoutInflater)
    }

    override fun initViews() {

    }

    override fun onResume() {
        super.onResume()
        isResume = true
    }

    override fun onPause() {
        super.onPause()
        isResume = false
    }

    override fun onDestroy() {
        binding.lavLoading.cancelAnimation()
        oxInterstitialAdHelper?.destroyAd()
        super.onDestroy()
    }

    override fun onBackPressed() {
    }

    private fun loadInterstitialAd() {
        if (!MMKV.defaultMMKV().decodeBool(IS_CLICKED_GET_STARTED_BTN)
            || AiChatApplication.app.appViewModel.isSubscribed()
        ) {
            return
        }
        binding.lavLoading.visibility = View.VISIBLE
        val adConfig = AdUtils.getSplashInterstitialAdConfig(this)
        oxInterstitialAdHelper = OxInterstitialAdHelper.createAd(this, adConfig.adId)
        oxInterstitialAdHelper?.run {
            setAdListener(object : InterstitialAdListener() {
                override fun onAdClosed() {
                    super.onAdClosed()

                    startToNextActivity()
                }

                override fun onAdDisplayed() {
                    super.onAdDisplayed()
                    binding.lavLoading.cancelAnimation()
                    binding.lavLoading.visibility = View.GONE
                }

                override fun onAdDisplayFailed(p0: String?, p1: String?) {
                    super.onAdDisplayFailed(p0, p1)

                    startToNextActivity()
                }
            })
            loadAd(adConfig.adPlacement)
        }
    }

    private fun showInterstitialAd() {
        val adConfig = AdUtils.getSplashInterstitialAdConfig(this)
        oxInterstitialAdHelper?.showAd(adConfig.adPlacement)
    }

    private fun startToNextActivity() {
        // AdMob 平台下，在广告 show 时，点 home 按键退到后台，广告会自己关闭掉，这时候如果不判断应用是否在前台的话，
        // 就会在后台弹出 MainActivity 或者 LanguageActivity
        if (!AiChatApplication.app.isAppForeground()) {
            finish()
            return
        }
        if (LanguageUtils.isLanguageSet()) {
            startMainActivity()
        } else {
            startLanguageActivity()
        }
    }

    private fun startMainActivity() {
        startActivity(Intent(this, MainActivity::class.java))
        finish()
    }

    private fun startLanguageActivity() {
        startActivity(Intent(this, LanguageActivity::class.java))
        finish()
    }
}